﻿using Library.API.C5.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Library.API.C5.Filters
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class CheckAuthorExistFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 注入仓库
        /// </summary>
        /// <param name="repositoryWrapper"></param>
        public CheckAuthorExistFilterAttribute(IRepositoryWrapper repositoryWrapper)
        {
            RepositoryWrapper = repositoryWrapper;
        }

        public IRepositoryWrapper RepositoryWrapper { get; }

        /// <summary>
        /// 执行控制器方法前设置
        /// 验证authorId作者是否存在，不存在返回404，存在执行正常的控制器方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var authorIdParameter = context.ActionArguments.Single(m => m.Key == "authorId");
            Guid authorId = (Guid)authorIdParameter.Value;

            var isExist = await RepositoryWrapper.Author.IsExistAsync(authorId);
            if (!isExist)
            {
                context.Result = new NotFoundResult();
            }

            await base.OnActionExecutionAsync(context, next);
        }
    }
}